package com.orhon.smartcampus.modules.systemctl.mutation;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.systemctl.dao.ApisDao;
import com.orhon.smartcampus.modules.systemctl.dao.ModulesDao;
import com.orhon.smartcampus.modules.systemctl.entity.Apis;
import com.orhon.smartcampus.modules.systemctl.entity.Modules;
import com.orhon.smartcampus.modules.systemctl.gqlInputModel.GQLApiInput;
import com.orhon.smartcampus.modules.systemctl.inputMapper.ApiInputMapper;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class AddApiMutation implements DataFetcher {

	@Autowired
	ApisDao apisDao;
	@Autowired
	ModulesDao modulesDao;


	public Object get(DataFetchingEnvironment env) throws Exception {
		GQLApiInput input = ApiInputMapper.MAPPER.mapInput(env.getArgument("inputData"));

		Apis api = null;

		if (input.getId() != null) {
			api = apisDao.get(Apis.class, input.getId());
			api.setUpdatedAt(new Date());
		} else {
			api = new Apis();
			api.setCreatedAt(new Date());
		}

		if(input.getCode() != null) {
			api.setCode(input.getCode());
		}
		if(input.getName() != null) {
			api.setName(input.getName());
		}
		if(input.getModule_id() != null) {
			api.setModule(modulesDao.get(Modules.class, input.getModule_id()));
		}
		try{
			apisDao.saveOrUpdate(api);
		}
		catch (Exception e){
			System.out.println(e);
			return Result.error(500,""+e);
		}
		return api;
	}
}

